<template>
  <div>
    <zm-panel title="产品退货" :visible.sync="value" @change="close">
      <zm-form label-width="100px" :model="form" :rules="rules" ref="form">
        <zm-form-item label="" label-width="0px">
          <zm-table-data :data="form.wenlvRule.list" :show-page="false" :border="false" :stripe="false" class="mb20">
            <zm-table-column prop="typeName" label="活动类型" fixed="left" min-width="120">
              <template slot-scope="scope">
                <div>{{ scope.row.typeName }}</div>
              </template>
            </zm-table-column>
            <zm-table-column prop="calculationMethodName" label="销售总额计算方式" fixed="left" min-width="120">
              <template slot-scope="scope">
                <div>{{ scope.row.calculationMethodName }}</div>
              </template>
            </zm-table-column>
            <zm-table-column prop="address" label="活动场地" fixed="left" min-width="120">
              <template slot-scope="scope">
                <div>{{ scope.row.address }}</div>
              </template>
            </zm-table-column>
            <zm-table-column prop="endTime" label="活动时间" fixed="left" min-width="120">
              <template slot-scope="scope">
                <div>{{ scope.row.startTime }}--{{ scope.row.endTime }}</div>
              </template>
            </zm-table-column>
            <zm-table-column prop="unitPrice" label="销售单价（元）" fixed="left" min-width="120">
              <template slot-scope="scope">
                <div>
                  {{
                    scope.row.calculationMethod === "1"
                      ? scope.row.unitPrice
                      : "--"
                  }}
                </div>
              </template>
            </zm-table-column>
            <zm-table-column prop="totalSalePrice" label="可退金额（元）" fixed="left" min-width="120">
              <template slot-scope="scope">
                <div>{{ scope.row.totalSalePrice }}</div>
              </template>
            </zm-table-column>
            <zm-table-column prop="joinCount" label="可退数量（人）" fixed="left" min-width="120">
              <template slot-scope="scope">
                <div>
                  {{
                    scope.row.calculationMethod === "1"
                      ? scope.row.joinCount
                      : "--"
                  }}
                </div>
              </template>
            </zm-table-column>
            <zm-table-column prop="refundNumber" label="退货数量（人）" fixed="left" min-width="120">
              <template slot-scope="scope">
                <el-input type="number" v-model="scope.row.refundNumber" :min="0" :max="scope.row.joinCount" placeholder="0" @input.native="
                    backNumChange(
                      $event,
                      scope.row.refundNumber,
                      scope.$index,
                      'refundNumber',
                      'joinCount'
                    )
                  " v-if="scope.row.calculationMethod === '1'"
                  :disabled="+scope.row.joinCount === 0"
>
                </el-input>
                <div v-else>{{ "--" }}</div>
              </template>
            </zm-table-column>
            <zm-table-column prop="refundAmount" label="退货金额（元）" fixed="left" min-width="120">
              <template slot-scope="scope">
                <el-input type="number" v-model="scope.row.refundAmount" :min="0" :max="scope.row.totalSalePrice" placeholder="0.00" @input.native="
                    backNumChange(
                      $event,
                      scope.row.refundAmount,
                      scope.$index,
                      'refundAmount',
                      'totalSalePrice'
                    )" v-if="scope.row.calculationMethod === '2'" :disabled="
                    (scope.row.calculationMethod === '2' &&
                      +scope.row.totalSalePrice === 0) ||
                      (scope.row.calculationMethod === '1' &&
                        +scope.row.joinCount === 0)
                  "
>
                </el-input>
                <div v-else>{{ scope.row.refundAmount || "--" }}</div>
              </template>
            </zm-table-column>
          </zm-table-data>
        </zm-form-item>
        <zm-form-item label="退款总额：" prop="saleTotalPrice">
          ￥{{ saleTotalPrice || "0.00" }}
        </zm-form-item>
        <zm-form-item label="退货说明：" prop="remark">
          <zm-input type="textarea" v-model="form.remark" maxlength="300" :autosize="{ minRows: 4, maxRows: 6 }" show-word-limit placeholder="请输入使退货说明，便于审批人员查看" />
        </zm-form-item>
      </zm-form>
      <div slot="footer" class="tr">
        <el-button @click="close">返回</el-button>
        <el-button type="primary" @click="submit">提交审批</el-button>
      </div>
    </zm-panel>
  </div>
</template>

<script>
import panelMixin from '@/mixins/panelMixin'
import saleOrder from '@/api/src/saleOrder'
import approveProcessApis from '@/api/src/approve'
export default {
  components: {},
  mixins: [panelMixin],
  props: {
    obj: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    return {
      form: {
        wenlvRule: {
          list: []
        },

        remark: ''
      },
      saleTotalPrice: '0',
      rules: {
        remark: { required: true, message: '请输入', trigger: 'blur' }
      }
    }
  },
  computed: {},
  created () {
    this.obj.id && this.getDetail()
  },
  methods: {
    async getDetail () {
      this.form = await saleOrder.getRefund({ orderId: this.obj.id })
    },
    countTotal (arr, keyPrice) {
      let $total = 0
      $total = arr.reduce((total, currentValue, currentIndex, arr) => {
        return +currentValue[keyPrice] ? total + +currentValue[keyPrice] : total
      }, 0)
      console.log($total.toFixed(2), 'total')
      return $total.toFixed(2)
    },
    backNumChange (e, val, idx, refundKey, totalKey) {
      const res = this.form.wenlvRule.list.find(item => {
        return +item[refundKey] > +item[totalKey]
      })

      /* if (this.form.wenlvRule.list[idx][refundKey] === '') {
        this.form.wenlvRule.list[idx][refundKey] = 0
      } */

      if (res) {
        // this.$message.warning('退货数量不能大于可退数量')
        this.$set(
          this.form.wenlvRule.list[idx],
          refundKey,
          this.form.wenlvRule.list[idx][totalKey]
        )
      }

      let reg = new RegExp(/^[0-9]+$/).test(this.form.wenlvRule.list[idx].refundNumber)
      if (this.form.wenlvRule.list[idx].calculationMethod === '1' && !reg) {
        // this.$message.warning('请输入正整数')
        this.$set(this.form.wenlvRule.list[idx], 'refundNumber', '')
      }

      this.form.wenlvRule.list.map(item => {
        if (item.calculationMethod === '1') {
          item.refundAmount = (
            (+item.refundNumber || 0) * (+item.unitPrice || 0)
          ).toFixed(2)
        }
      })

      this.saleTotalPrice =
        +this.countTotal(this.form.wenlvRule.list, 'refundAmount') || 0
    },
    async submit () {
      let _valid = false
      this.$refs.form.validate(valid => {
        _valid = valid
      })
      if (!_valid) {
        return
      }

      /* let renfundList = []
      this.form.wenlvRule.list.forEach((item, index) => {
        this.$set(renfundList, index, {
          id: item.id,
          name: item.name,
          price: item.price,
          canBackNum: item.canBackNum,
          unBackNum: item.unBackNum,
          refundNum: item.backNum,
          refundAmount: (+item.price * +item.backNum).toFixed(2)
        })
      })
      const params = {
        orderId: this.obj.id,
        remark: this.form.remark,
        refundwenlvRule.list: refundwenlvRule.list
      } */
      const form = {
        ...this.form,
        ...{ orderId: this.form.id },
        ...{ refundProductList: this.form.wenlvRule }
      }
      saleOrder.refund(form).then(async result => {
        await approveProcessApis.submit({
          businessId: result.id,
          processType: '6',
          linkName: this.form.orderNo + this.form.customerName
        })
        this.$message.success('操作成功')
        this.close()
      })
    }
  }
}
</script>
